<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="dialog"
    :close-on-click-modal="false"
    title="PLU"
    append-to-body
    width="95%"
    @close="cancel"
  >
    <div class="app-container">
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchUpdate">保存</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchValidate">批量校验</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doSubmitBPMS">提交审核</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="downloadExcelTemplate(parent.$route.name, 1)">下载导入模板</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="exportTempDataExcel(data, parent.$route.name)">导出</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchCreate">保存</el-button>
      <el-button class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doReadInfo">获取Item信息</el-button>
      <div v-if="createFlag === true" style="margin-bottom:5px;">
        <el-form :inline="true" size="small" label-width="auto">
          <el-form-item label="部门号,PLU#：">
            <el-input v-model="itemNbrTxt" placeholder="输入部门号和PLU#以英文半角逗号分隔，一行为一条数据" rows="5" type="textarea" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="采购ID：">
            <el-select v-model="buyerId" style="width: 280px;">
              <el-option v-for="bid in buyerList" :key="bid" :label="bid" :value="bid" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="data" stripe size="small" border :height="tableHeight" style="width: 100%;" @header-dragend="colChange">
        <el-table-column type="index" align="center" fixed width="55" label="序号" />
        <el-table-column v-if="createFlag === true" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">移除该项</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="createFlag === false" label="校验信息">
          <template slot-scope="scope">
            <!--<el-popover
              v-if="scope.row.errorMsg && JSON.parse(scope.row.errorMsg).length > 0"
              placement="bottom"
              title="校验信息"
              trigger="click"
            >
              <div style="height:400px;overflow:auto;">
                <div v-for="(msg,index) in JSON.parse(scope.row.errorMsg)" :key="index" :index="index">
                  <span>{{ (index + 1) + '.' + msg }}</span>
                </div>
              </div>
              <el-button slot="reference" size="mini" type="text" style="color:#fc1111">点击查看</el-button>
            </el-popover>-->
            <validateMsg :item="scope.row" :type="3" />
          </template>
        </el-table-column>
        <el-table-column label="部门号" prop="deptNbr" :width="colWidths.deptNbr" />
        <el-table-column label="商品号" prop="itemNbr" :width="colWidths.itemNbr">
          <template slot-scope="scope">
            <el-input v-model="scope.row.itemNbr" class="filter-item" :width="colWidths.itemNbr" />
          </template>
        </el-table-column>
        <el-table-column label="PLU#" prop="pluNbr" :width="colWidths.pluNbr" />
        <el-table-column label="固定重量" prop="fixedWeight" :width="colWidths.fixedWeight" />
        <el-table-column label="CHG_固定重量" prop="chg_fixedWeight" :width="colWidths.chg_fixedWeight">
          <template slot-scope="scope">
            <el-input v-model="scope.row.chg_fixedWeight" class="filter-item" :width="colWidths.chg_fixedWeight" />
          </template>
        </el-table-column>
        <el-table-column label="最佳食用期" prop="shelfLife" :width="colWidths.shelfLife" />
        <el-table-column label="CHG_最佳食用期" prop="chg_shelfLife" :width="colWidths.chg_shelfLife">
          <template slot-scope="scope">
            <el-input v-model="scope.row.chg_shelfLife" class="filter-item" :width="colWidths.chg_shelfLife" />
          </template>
        </el-table-column>
        <el-table-column label="皮重" prop="tareWeight" :width="colWidths.tareWeight" />
        <el-table-column label="CHG_皮重" prop="chg_tareWeight" :width="colWidths.chg_tareWeight">
          <template slot-scope="scope">
            <el-input v-model="scope.row.chg_tareWeight" class="filter-item" :width="colWidths.chg_tareWeight" />
          </template>
        </el-table-column>
        <el-table-column label="配料表" prop="chargeMixtureForm" :width="colWidths.chargeMixtureForm" />
        <el-table-column label="CHG_配料表" prop="chg_chargeMixtureForm" :width="colWidths.chg_chargeMixtureForm">
          <template slot-scope="scope">
            <el-input v-model="scope.row.chg_chargeMixtureForm" class="filter-item" :width="colWidths.chg_chargeMixtureForm" />
          </template>
        </el-table-column>
        <el-table-column label="商品说明" prop="pluDesc" :width="colWidths.pluDesc" />
        <el-table-column label="CHG_商品说明" prop="chg_pluDesc" :width="colWidths.chg_pluDesc">
          <template slot-scope="scope">
            <el-input v-model="scope.row.chg_pluDesc" class="filter-item" :width="colWidths.chg_pluDesc" />
          </template>
        </el-table-column>
        <el-table-column label="是否自制" prop="selfFlag" :width="colWidths.selfFlag">
          <template slot-scope="scope">
            <el-input v-model="scope.row.selfFlag" class="filter-item" :width="colWidths.selfFlag" />
          </template>
        </el-table-column>
        <el-table-column label="附件" prop="filePath" :width="colWidths.filePath">
          <template slot-scope="scope">
            <i v-if="scope.row.filePath" class="el-icon-picture" style="font-size:23px;margin-right: 3px;" @click="previewFile(scope.row.filePath)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <urgentForm ref="urgentForm" :parent="parent" />
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { parseTime } from '@/utils/index'
import { batchUpdateItem, batchCreatePLUItem, queryPLUList, batchValidate, queryList } from '@/api/change-item'
import urgentForm from './urgent'
import { previewFile, exportTempDataExcel, downloadExcelTemplate } from '@/utils/item'
import initTable from '@/utils/initTable'
import validateMsg from '@/views/part/validateMsg'

export default {
  components: { urgentForm, validateMsg },
  mixins: [initTable],
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      data: [],
      loading: false,
      tableHeight: window.innerHeight * 0.7,
      createFlag: false,
      iparent: this,
      itemNbrTxt: '',
      buyerList: [],
      buyerId: ''
    }
  },
  methods: {
    previewFile,
    exportTempDataExcel,
    downloadExcelTemplate,
    cancel() {
      this.data = []
      this.itemNbrTxt = ''
      this.buyerList = []
      this.buyerId = ''
    },
    // 修改保存触发
    doBatchUpdate() {
      this.$confirm('是否变更该 ' + this.data.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const val = []
        this.data.forEach(item => {
          item.changeTime = parseTime(new Date())
          val.push({ id: item.id, itemInfo: JSON.stringify(item) })
        })
        batchUpdateItem(val).then(() => {
          Message({
            message: '保存成功。',
            type: 'success',
            duration: 3 * 1000
          })
          this.parent.toQuery()
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    },
    // 删除一行
    deleteRow(index) {
      this.data.splice(index, 1)
    },
    // 保存触发
    doBatchCreate() {
      if (this.data.length < 1) {
        Message({
          message: '请编辑需要新增的PLU信息。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('是否新增该 ' + this.data.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const val = []
          this.data.forEach(item => {
            item.changeTime = parseTime(new Date())
            val.push({ id: '', buyerId: this.buyerId, itemInfo: JSON.stringify(item) })
          }, (error) => {
            console.log(error)
            this.loading = false
          })
          batchCreatePLUItem(val).then(() => {
            Message({
              message: '新增成功。',
              type: 'success',
              duration: 3 * 1000
            })
            this.parent.toQuery()
            this.loading = false
            this.dialog = false
          }, (error) => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 读取数据
    doReadInfo() {
      if (this.createFlag === true && (!this.itemNbrTxt || this.itemNbrTxt === '')) {
        Message({
          message: '请编辑需要修改的PLU。',
          type: 'error',
          duration: 3 * 1000
        })
      } else if (this.itemNbrTxt.length > 1000) {
        Message({
          message: '所需获取的信息过多，请使用Excel导入方式进行操作。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.loading = true
        let _itemNbrTxt = this.itemNbrTxt.trim() // 去掉两头空格
        _itemNbrTxt = _itemNbrTxt.replace(/[\n\r\s]/g, '-')
        const sourceData = []
        for (let i = 0; i < this.data.length; i++) {
          sourceData.push(this.data[i])
        }
        const itemArray = _itemNbrTxt.split('-')
        itemArray.forEach(_itemNbr => {
          if (_itemNbr && _itemNbr !== '') {
            const itemArray2 = _itemNbr.trim().split(',')
            if (itemArray2[0] && itemArray2[1]) {
              this.data.push({ deptNbr: itemArray2[0], pluNbr: itemArray2[1] })
            } else {
              Message({
                message: '单行数据必须包含部门与PLU#。',
                type: 'error',
                duration: 3 * 1000
              })
            }
          }
        })
        const indexRemoveDate = []
        const paramList = []
        this.data.forEach(plu => {
          paramList.push({ deptNbr: plu.deptNbr, pluNbr: plu.pluNbr })
        })
        queryPLUList(paramList).then(res => {
          if (res) {
            res.forEach(dbPlu => {
              for (let i = 0; i < this.data.length; i++) {
                if (this.data[i].deptNbr.toString() === dbPlu.deptNbr.toString() && this.data[i].pluNbr.toString() === dbPlu.pluNbr.toString()) {
                  const obj = this.data[i]
                  obj.fixedWeight = dbPlu.fixedWeight
                  obj.shelfLife = dbPlu.shelfLife
                  obj.tareWeight = dbPlu.tareWeight
                  obj.chargeMixtureForm = dbPlu.chargeMixtureForm
                  obj.pluDesc = dbPlu.pluDesc
                  obj.itemNbr = obj.itemNbr ? obj.itemNbr : dbPlu.itemNbr
                  this.data.splice(i, 1, obj)
                  indexRemoveDate.push(i)
                }
              }
            })
            let deletFalge = 0
            var errorItem = ''
            for (let i = 0; i < this.data.length; i++) {
              if (indexRemoveDate.indexOf(i + deletFalge) === -1) {
                errorItem = errorItem + '部门号：' + this.data[i].deptNbr.toString() + ' PLU#:' + this.data[i].pluNbr.toString() + ','
                this.data.splice(i, 1)
                i -= 1
                deletFalge += 1
              }
            }
            if (errorItem && errorItem.length > 0) {
              Message({
                message: '无效PLU：' + errorItem.substring(0, errorItem.length - 1),
                type: 'warning',
                duration: 3 * 1000
              })
            }
          }
          this.loading = false
        }, (error) => {
          console.log(error)
          this.data = sourceData
          this.loading = false
        })
      }
    },
    // 批量提交审核前置
    doSubmitBPMS() {
      if (this.data.length < 1) {
        Message({
          message: '请选择需要提交审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        const _this = this.$refs.urgentForm
        _this.itemSize = this.data.length
        _this.changeType = this.parent.$route.name
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        _this.bpmsParam.auditBuyerId = this.parent.auditBuyerId
        _this.ids = ids
        _this.dialog = true
      }
    },
    // 批量校验
    doBatchValidate() {
      this.$confirm('确认校验该 ' + this.data.length + ' 条item信息?', '校验数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        batchValidate({ ids: ids, changeType: this.parent.$route.name }).then(res => {
          queryList({ ids: ids, changeType: this.parent.$route.name }).then(dataList => {
            if (dataList) {
              const _data = []
              dataList.forEach(dataObj => {
                _data.push(JSON.parse(dataObj.itemInfo))
              })
              this.data = _data
            }
          })
          this.parent.toQuery()
          Message({
            message: '校验处理中，请稍后刷新页面进行查询。',
            type: 'success',
            duration: 3 * 1000
          })
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    }
  }
}
</script>

